<template>
  <div class="file-uploader el-input">
    <template v-if="fileList && fileList.length">
      <div v-for="(file, index) in fileList" :key="index" class="file-uploader-file-item">
        <template v-if="file">
          <i :style="{ backgroundImage: `url(${getFileIcon(file.fileType)})` }" class="file-icon"></i>
          <span class="flex-item ellipsis-1" style="overflow: hidden">{{ file.fileName }}</span>
          <span>（{{ file.fileSize | formatSize }}）</span>
          <ElButton style="margin-right: 10px" type="text" @click="download([file.id], { fileName: file.fileName })">
            下载
          </ElButton>
          <span v-if="!inputDisabled" class="handle-buttons">
            <ElButton size="small" type="text" @click="handleClick(file)">重新选择</ElButton>
            <ElButton icon="el-icon-delete" type="text" @click="removeFile(file)" />
          </span>
        </template>
      </div>
    </template>
    <EmptyView
      v-else-if="inputDisabled"
      font-size="14px"
      style="margin-top: 10px; background-color: #f5f7fa; border: 1px solid #e4e7ed; border-radius: 4px"
      empty-tips="暂无文件" />
    <ElUpload
      v-show="!inputDisabled && (!fileList || fileList.length < limit)"
      ref="upload"
      :action="action"
      :before-upload="beforeUploadFile"
      :data="{ unid: innerUnId, type: fileLabel }"
      :headers="headers"
      :accept="accept"
      :on-success="onFileUploadSuccess"
      :show-file-list="false"
      auto-upload
      class="custom-uploader"
      drag>
      <i class="el-icon-plus"></i>
      <slot name="tips">请选择上传文件(最多{{ limit }}个)、限制每个{{ limitSize }}MB以内</slot>
    </ElUpload>
  </div>
</template>

<script>
  import {
    findAllByParentUnid,
    getUploadUrlNocert,
    getHeader,
    getUploadUrl,
    download,
    remove
  } from '@/api/attachment/attachment'
  import { getFileSuffix, guid } from '@web-utils/core'
  import { getFileIcon } from '@/util'

  export default {
    name: 'FileUploader',
    inject: {
      elForm: {
        default: ''
      },
      elFormItem: {
        default: ''
      }
    },
    props: {
      unid: String,
      prop: {
        type: String,
        default: ''
      },
      limit: {
        type: Number,
        default: 1
      },
      limitSize: {
        type: Number,
        default: 20
      },
      disabled: Boolean,
      accept: {
        type: String,
        default: '*/*'
      },
      value: Array,
      cert: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        curFile: null,
        fileList: [],
        innerUnId: ''
      }
    },
    computed: {
      fileLabel() {
        if (this.prop) {
          return this.prop
        } else if (this.elFormItem) {
          return this.elFormItem.prop
        } else {
          return ''
        }
      },
      inputDisabled() {
        return this.disabled || (this.elForm || {}).disabled
      },
      action() {
        if (this.cert) {
          return getUploadUrl()
        } else {
          return getUploadUrlNocert()
        }
      },
      headers() {
        if (this.cert) {
          return getHeader()
        } else {
          return {}
        }
      }
    },
    watch: {
      unid: {
        immediate: true,
        async handler(newVal) {
          this.innerUnId = newVal
        }
      },
      value: {
        immediate: true,
        handler(newVal) {
          // if (!this.cert) {
          this.fileList = newVal
          // }
          // if (!this.unid && this.fileList && this.fileList.length) {
          //   this.innerUnId = this.fileList[0].parentUnid
          // }
        }
      },
      innerUnId: {
        immediate: true,
        async handler() {
          if (this.cert) {
            await this.fetchAttachments()
          }
        }
      },
      fileList(newVal) {
        this.$emit('files-change', newVal)
      }
    },
    methods: {
      download,
      getFileIcon,
      getFileList() {
        return this.fileList
      },
      submit() {
        this.$refs.upload.submit()
      },
      handleClick(file) {
        this.curFile = file
        this.$refs.upload.$refs['upload-inner'].handleClick()
      },
      async onFileUploadSuccess(res) {
        if (this.curFile) {
          const index = this.fileList.findIndex(value => value.id === this.curFile.id)
          if (index > -1) {
            await this.deleteFile(this.curFile)
            this.fileList.splice(index, 1, res.data)
          }
        } else {
          if (!this.fileList) {
            this.fileList = []
          }
          this.fileList.push(res.data)
        }
      },
      async beforeUploadFile(file) {
        if (this.accept !== '*/*') {
          if (!this.accept.split(',').includes(getFileSuffix(file.name, true))) {
            this.$message.warning(`只允许上传${this.accept}格式的文件！`)
            return Promise.reject(new Error(`只允许上传${this.accept}格式的文件！`))
          }
        }
        if (file.size / (1024 * 1024) > this.limitSize) {
          this.$message.warning(`上传文件不能超过${this.limitSize}M!`)
          return Promise.reject(new Error(`上传文件不能超过${this.limitSize}M!`))
        }
        await this.fetchUnId()
        this.$emit('before-upload-file', file)
      },
      async deleteFile(row) {
        const res = await remove(row.id)
        // const res = await noauthRemove(row.id)
        return res.code === 0
      },
      async removeFile(row) {
        const success = await this.deleteFile(row)
        if (success) {
          this.fileList = this.fileList.filter(value => value !== row)
        }
      },
      async fetchUnId() {
        if (!this.innerUnId || this.innerUnId === '') {
          const unid = guid()
          this.$emit('unid-created', unid)
          this.innerUnId = unid
        }
      },
      async fetchAttachments() {
        if (this.innerUnId && this.innerUnId !== '') {
          const { data } = (await findAllByParentUnid(this.innerUnId, this.fileLabel)) || {}
          this.fileList = data || []
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep.file-uploader {
    width: 100%;
    overflow: hidden;

    .file-uploader-file-item {
      display: flex;
      align-items: center;
      height: 36px;
      margin-bottom: 6px;
      padding-right: 10px;
      padding-left: 10px;
      color: #808080;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }

      .handle-buttons {
        .el-button--primary {
          color: var(--color-primary);
        }

        .el-button--danger {
          color: #f56c6c;
        }
      }
    }

    .file-icon {
      display: inline-block;
      width: 24px;
      min-width: 24px;
      height: 24px;
      margin-right: 6px;
      background-repeat: no-repeat;
    }

    .custom-uploader {
      .el-upload {
        display: block;
        width: 100%;
        height: 100%;
        text-align: left;
        border: 1px dashed #ccc;
      }

      .el-upload-dragger {
        display: block;
        width: 100%;
        height: 100%;
        padding-right: 10px;
        padding-left: 10px;
        text-align: left;
        border: none;
        border-radius: 0;
      }
    }

    .custom-uploader,
    .el-upload-dragger,
    .el-upload {
      display: block;
      width: 100%;
      height: 36px;
      line-height: 36px;
    }

    .el-icon-plus {
      margin-right: 10px;
    }
  }
</style>
